package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())  ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");

        }



        //2.根据用户名检查用户信息

        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));


        //null 不存在
        if (list == null || list.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");


        }

        //非null，判断密码
        AdUser adUser = list.get(0);


        //将密码加盐，md5加密 对比
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());




        //一致 生成tojen
        if (password.equals(adUser.getPassword())){
            String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
            Map map = new HashMap<>();
            map.put("token",token);
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);

        }



        //不一致 返回密码错误
        else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }




    }
}
